package cn.fetosoft.woodpecker.controller;

import cn.fetosoft.woodpecker.core.pubsub.Command;
import cn.fetosoft.woodpecker.core.pubsub.Publication;
import cn.fetosoft.woodpecker.core.pubsub.Subscription;
import cn.fetosoft.woodpecker.core.pubsub.zookeeper.NodeEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;

/**
 * 节点管理
 * @author guobingbing
 * @wechat t_gbinb
 * @since 2021/9/13 21:29
 */
@Slf4j
@Controller
@RequestMapping("/auth/cluster")
public class ClusterController {

    @Autowired
    private Publication publication;
    @Autowired
    private Subscription subscription;

    /**
     * 采样数据页面
     * @return
     */
    @RequestMapping("/index")
    public String clusterPage(){
        return "/cluster/index";
    }

    /**
     * 获取所有节点
     * @return
     */
    @RequestMapping("/getClusters")
    @ResponseBody
    public String getClusters(){
        Result<List<NodeEntity>> result = Result.errorResult();
        try {
            List<NodeEntity> list = subscription.getRegisterClusters();
            result.setObj(list);
            result.setStatus(Result.SUCCESS);
        } catch (Exception e) {
            result.setErrorMsg(e.getMessage());
            log.error("getClusters", e);
        }
        return result.toString();
    }

    /**
     * 是否启用节点
     * @return
     */
    @PostMapping("/enabled")
    @ResponseBody
    public String enabled(@RequestParam String clusterId, @RequestParam boolean enabled){
        Result<String> result = Result.errorResult();
        try{
            Command cmd = new Command();
            cmd.setCommand(Command.CMD_ENABLED);
            cmd.setClusterId(clusterId);
            cmd.setEnabled(enabled);
            publication.publish(cmd.toString());
            result.setStatus(Result.SUCCESS);
        }catch (Exception e){
            result.setErrorMsg(e.getMessage());
            log.error("enabled", e);
        }
        return result.toString();
    }
}
